package com.study.crud.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.study.crud.model.emp.Emp;
import com.study.crud.service.EmpService;
import com.study.crud.service.JobService;
import com.study.crud.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/emp")
public class EmpController {

    @Resource
    private EmpService empService;

    @Resource
    private UserService userService;

    @Resource
    private JobService jobService;

    @RequestMapping("/findAll")
    public String findAll(Model model){
        List<Emp> empList = empService.list(new QueryWrapper<>());
        model.addAttribute("empList",empList);
        return "emp/empList";
    }

    @RequestMapping("/toAdd")
    public String toAdd(){
        return "emp/addEmp";
    }

    @RequestMapping("/add")
    public String add(Emp emp){
        empService.save(emp);
        return "redirect:/emp/findAll";
    }

    @RequestMapping("/toUpdate")
    public String toUpdate(Integer eid,Model model){
        Emp emp = empService.getById(eid);
        model.addAttribute("emp",emp);
        return "emp/updateEmp";
    }

    @RequestMapping("/update")
    public String update(Emp emp){
        empService.updateById(emp);
        return "redirect:/emp/findAll";
    }

    @RequestMapping("/deleteByEid")
    public String deleteByEid(Integer eid){
        Integer num = userService.findNumByEid(eid);
        if (num==0){
            empService.removeById(eid);
            jobService.removeByEid(eid);
            return "redirect:/emp/findAll";
        }
        return "error/error_deleteEmp";
    }
}
